package com.imti.config;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imti.api.ResultCode;
import com.imti.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author T470S
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();
        if (requestURI.contains("/login") || requestURI.contains("/register") || requestURI.contains("/swagger-ui")){
            // 对于登录，注册，swagger访问放行
            return true;
        }

        String hospital_token = request.getHeader("hospital_token");
        Map<String,Object> infoMap = new HashMap<>();

        try{
            //token验证
            DecodedJWT tokenInfo = JwtUtils.getTokenInfo(hospital_token);

            return true;
        }catch (SignatureVerificationException e){
            e.printStackTrace();
            infoMap.put("message","无效签名");
        }catch (TokenExpiredException e){
            infoMap.put("message","token已过期");
        }catch (AlgorithmMismatchException e){
            infoMap.put("message","算法不一致");
        }catch (Exception e){
            infoMap.put("message","无效签名");
        }
        infoMap.put("code", ResultCode.UNAUTHORIZED.getCode());
        infoMap.put("data", Collections.EMPTY_LIST);
        ObjectMapper objectMapper = new ObjectMapper();
        String mapInfoJson = objectMapper.writeValueAsString(infoMap);
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(mapInfoJson);
        return false;
    }
}
